package com.party.mobile.web.controller.analysis;

import com.party.common.utils.DateUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.analysis.StatisticsEvent;
import com.party.core.service.analysis.IStatisticsEventService;
import com.party.core.service.analysis.IStatisticsPageFlowService;
import com.party.mobile.biz.analysis.StatisticalEventFlowBizService;
import com.party.mobile.biz.analysis.StatisticsFlowBizService;
import com.party.mobile.biz.analysis.StatisticsUserBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.analysis.EventFlowInput;
import com.party.mobile.web.dto.analysis.PageFlowInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

/**
 * 分析流程
 *
 * @author yifeng
 * @date 2018/8/3 0003
 * @time 下午 16:56
 */
@Controller
@RequestMapping("analysis/flow")
public class StatisticalFlowController {
    @Autowired
    private IStatisticsPageFlowService statisticsPageFlowService;
    @Autowired
    private StatisticsFlowBizService statisticsFlowBizService;
    @Autowired
    private StatisticalEventFlowBizService statisticalEventFlowBizService;
    @Autowired
    private IStatisticsEventService statisticsEventService;
    @Autowired
    private StatisticsUserBizService statisticsUserBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 进入页面时保存记录
     *
     * @param flowInput 输入参数
     * @param response  response
     * @param request   request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "innerPageDataReport")
    public void innerPageDataReport(PageFlowInput flowInput, HttpServletResponse response, HttpServletRequest request) throws IOException {
        try {
            //获取当前访问用户的userId
            String userId = statisticsUserBizService.userLoginRecordOperation("", "", "", request);
            if (StringUtils.isEmpty(userId)) {
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "用户编号不能为空");
            }
            flowInput.setUserId(userId);

            String uniqueCode = statisticsFlowBizService.getCookieByKey(request, statisticsFlowBizService.pageRedisKey);
            if (StringUtils.isEmpty(flowInput.getLastHtmlUrl()) || StringUtils.isEmpty(uniqueCode)) {
                /**
                 * 如果上个页面为空，说明是新的一次访问。则重新生成一次uniqueCode
                 */
                uniqueCode = statisticsFlowBizService.getUniqueCode(flowInput.getHtmlUrl(), userId);
            }
            flowInput.setUniqueCode(uniqueCode);

            Cookie cookie = new Cookie(statisticsFlowBizService.pageRedisKey, uniqueCode);
            cookie.setPath("/");
            response.addCookie(cookie);

            /**
             * 如果uniqueCode为空，上一次的记录id为空，说明之前访问过
             * 如果之前访问的记录isEnd不是结束，更新为结束
             */
//            if (StringUtils.isEmpty(flowInput.getParentId()) && StringUtils.isNotEmpty(flowInput.getFlowId())) {
//                try {
//                    StatisticsPageFlow lastPageFlow = statisticsPageFlowService.get(flowInput.getFlowId());
//                    if (lastPageFlow != null && !YesNoStatus.YES.getCode().equals(lastPageFlow.getIsEnd())) {
//                        lastPageFlow.setIsEnd(YesNoStatus.YES.getCode());
//                        statisticsPageFlowService.update(lastPageFlow);
//                    }
//                } catch (Exception e) {
//                    logger.error("更新上次访问记录isEnd为1失败", e);
//                }
//            }

            if (flowInput.getHtmlUrl().indexOf("loading.html") != -1) {
                Cookie flowCookie = new Cookie(statisticsFlowBizService.pageFlowRedisKey, "-1");
                flowCookie.setPath("/");
                response.addCookie(flowCookie);
            } else {
                String flowId = statisticsFlowBizService.insertPageFlow(flowInput, request);
                Cookie flowCookie = new Cookie(statisticsFlowBizService.pageFlowRedisKey, flowId);
                flowCookie.setPath("/");
                response.addCookie(flowCookie);
            }
        } catch (Exception e) {
            logger.error("进入页面时触发接口异常", e);
        }
        BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
        ImageIO.write(image, "png", response.getOutputStream());
    }

    /**
     * 进入页面时更新机构id
     *
     * @param flowInput 输入参数
     * @return
     */
    @ResponseBody
    @RequestMapping("updatePartnerId")
    public void updatePartnerId(PageFlowInput flowInput, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            statisticsFlowBizService.updatePagePartnerId(flowInput, request);
        } catch (Exception e) {
            logger.error("进入页面时更新机构id触发接口异常", e);
        }
        BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
        ImageIO.write(image, "png", response.getOutputStream());
    }

    /**
     * 离开页面时更新记录
     *
     * @param flowInput 输入参数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "outputPageDataReport")
    public void outputPageDataReport(PageFlowInput flowInput, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            statisticsFlowBizService.updatePageStayTime(flowInput, request);
        } catch (Exception e) {
            logger.error("离开页面时触发接口异常", e);
        }
        BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
        ImageIO.write(image, "png", response.getOutputStream());
    }

    /**
     * 统计事件流程,进入埋点页面时触发
     *
     * @param eventflowInput 输入参数
     * @param response       response
     * @param request        request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "innerEventFlowDataReport")
    public void innerEventFlowDataReport(EventFlowInput eventflowInput, HttpServletResponse response, HttpServletRequest request) throws IOException {
        String userId, code, pCode, orgId;
        try {
            //获取当前访问用户的userId
            userId = statisticsUserBizService.userLoginRecordOperation("", "", "", request);
            if (StringUtils.isEmpty(userId)) {
                throw new Exception("用户编号为空");
            }
            code = eventflowInput.getCode();
            pCode = eventflowInput.getpCode();
            orgId = eventflowInput.getOrgId();

            if ("".equalsIgnoreCase(code)) {
                throw new BusinessException(PartyCode.DATA_UNEXIST, "事件Code为空");
            }
            StatisticsEvent statisticsEvent = statisticsEventService.getByCode(code);
            if (null == statisticsEvent) {
                throw new BusinessException(PartyCode.DATA_UNEXIST, "事件Code不存在");
            }

            statisticalEventFlowBizService.innerEventFlowDataReport(statisticsEvent.getId(), pCode, orgId, userId, request, response);
        } catch (Exception e) {
            logger.error("统计事件流程,进入埋点页面触发接口异常", e);
        }
        BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
        ImageIO.write(image, "png", response.getOutputStream());
    }

    @ResponseBody
    @RequestMapping("test")
    public AjaxResult test() {
        String[] str = new String[]{
                "2018-08-21", "2018-08-22", "2018-08-23", "2018-08-24", "2018-08-25", "2018-08-26", "2018-08-27", "2018-08-28", "2018-08-29"
        };

        for (String s : str) {
            Date now = null;
            try {
                now = DateUtils.parse(s, "yyyy-MM-dd");
            } catch (ParseException e) {
                e.printStackTrace();
            }

            Date yesterday = DateUtils.addDay(now, -1);
            statisticsFlowBizService.analysisPage(yesterday);
        }
        return AjaxResult.success();
    }
}
